package com.pdg.dungeondelver.configuration;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.ResourceLoader;
import org.newdawn.slick.util.xml.XMLElement;
import org.newdawn.slick.util.xml.XMLElementList;
import org.newdawn.slick.util.xml.XMLParser;

public class DescriptorTable {
	private static final String TAG_TYPE = "type";
	private Map<String,Descriptor> descriptors = new HashMap<String,Descriptor>();
	public Descriptor get(String name){
		return descriptors.get(name);
	}
	public Set<String> keySet(){
		return descriptors.keySet();
	}
	private Theme theme;
	public Theme getTheme(){
		return theme;
	}
	private void setTheme(Theme theTheme){
		theme = theTheme;
	}
	public DescriptorTable(Theme theTheme,String ref) throws DescriptorTableLoadException{
		setTheme(theTheme);
		if(!loadFromXml(ref)){
			throw new DescriptorTableLoadException();
		}
	}
	private boolean loadFromXml(String ref) {
		XMLParser parser = new XMLParser();
		try {
			InputStream stream = ResourceLoader.getResourceAsStream(ref);
			XMLElement root = parser.parse(ref,stream);
			XMLElementList children = root.getChildren();
			for(Integer index=0;index<children.size();++index){
				XMLElement child = children.get(index);
				String name = child.getName();
				String type = child.getAttribute(TAG_TYPE);
				Object o = getTheme().getPropertySerializers().get(type).deserialize(child,getTheme().getThemes().getConfiguration());
				if(o instanceof Descriptor){
					descriptors.put(name, (Descriptor)o);
				}
			}
			return true;
		} catch (SlickException e) {
			e.printStackTrace();
			return false;
		}
	}
}
